package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.service.AdminAdCreateService;
import com.cskaoyan.market.service.AdminAdDeleteService;
import com.cskaoyan.market.service.AdminAdService;
import com.cskaoyan.market.service.AdminAdUpdateService;
import com.cskaoyan.market.service.impl.AdminAdCreateServiceImpl;
import com.cskaoyan.market.service.impl.AdminAdDeleteServiceImpl;
import com.cskaoyan.market.service.impl.AdminAdServiceImpl;
import com.cskaoyan.market.service.impl.AdminAdUpdateServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * @author Meltedicecream
 * @since 2023/06/19 20:57
 */
@WebServlet("/admin/ad/*")
public class AdminAdController extends HttpServlet {
    //查询的service
    private AdminAdService adService = new AdminAdServiceImpl();
    //删除的service
    private AdminAdDeleteService deleteService = new AdminAdDeleteServiceImpl();
    //新增的service
    private AdminAdCreateService createService = new AdminAdCreateServiceImpl();
    //修改的service
    private AdminAdUpdateService updateService = new AdminAdUpdateServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //分发
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/ad/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/ad/", "");
        if ("create".equals(op)) {
            create(req, resp);
        }
        if ("delete".equals(op)) {
            delete(req, resp);
        }
        if ("update".equals(op)) {
            update(req, resp);
        }
    }

    /**
     * 修改数据思路：1.获取相应参数并且判断参数合法性
     *               2.调用service根据id执行update的sql语句，并且返回一个marketad对象
     *               3.响应该对象
     * @param req
     * @param resp
     */
    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        //获取请求参数
        Integer id = JacksonUtil.parseInteger(reqBody, "id");
        String name = JacksonUtil.parseString(reqBody, "name");
        String url = JacksonUtil.parseString(reqBody, "url");
        String content = JacksonUtil.parseString(reqBody, "content");
        String link = JacksonUtil.parseString(reqBody, "link");
        Byte position = JacksonUtil.parseByte(reqBody, "position");
        Boolean enabled = JacksonUtil.parseBoolean(reqBody, "enabled");
        String addTime = JacksonUtil.parseString(reqBody, "addTime");
        String updateTime = JacksonUtil.parseString(reqBody, "updateTime");
        //判断参数合法性
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(url) || StringUtils.isEmpty(content) || id == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(404,"参数不完整")));
            return;
        }
        //调用service返回marketAd，并且响应出去
        MarketAd marketAd = updateService.update(id,name,url,content,link,position,enabled,addTime,updateTime);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketAd)));
    }

    /**
     * 删除思路：1.判断请求参数合法性
     * 2.解析js字符串封装成为对象
     * 3.数据库查询是否有该对象
     * 4.有则删除并且直接返回ok响应，无则返回ResponseUtil.badArgument()
     *
     * @param req
     * @param resp
     */
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        //通过id到数据库删除该条数据
        String id = JacksonUtil.parseString(reqBody, "id");
        if (StringUtils.isEmpty(id)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(404, "id不存在")));
            return;
        }
        int delete = deleteService.delete(id);
        if (delete == 1) {
            Object ok = ResponseUtil.ok();
            resp.getWriter().println(JacksonUtil.writeValueAsString(ok));
            return;
        }
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(404, "删除失败")));

    }

    /**
     * 新增广告思路：1.获取请求中的id ，name ，link，url，position，content，enabled，addTime，updateTime
     * 2.判断参数合法性
     * 3.调用service，在service中，将这些数据封装成对象(MarketAd)存入数据库并且返回
     * 4.将该对象响应出去
     *
     * @param req
     * @param resp
     */
    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        //获取请求参数
        String name = JacksonUtil.parseString(reqBody, "name");
        String url = JacksonUtil.parseString(reqBody, "url");
        String content = JacksonUtil.parseString(reqBody, "content");
        String link = JacksonUtil.parseString(reqBody, "link");
        Byte position = JacksonUtil.parseByte(reqBody, "position");
        Boolean enabled = JacksonUtil.parseBoolean(reqBody, "enabled");
//        String addTime = JacksonUtil.parseString(reqBody, "addTime");
//        String updateTime = JacksonUtil.parseString(reqBody, "updateTime");
        //判断参数合法性
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(url) || StringUtils.isEmpty(content)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(605, "参数填充不完整")));
            return;
        }
        //调用service返回一个MarketAd对象
        MarketAd marketAd = createService.create(name, url, content, link, position, enabled);
        //响应该对象
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketAd)));

    }


    /**
     * 展示所有广告与查找广告的功能实现
     * <p>
     * page:当前所在页
     * limint：每页固定的显示数量
     * sort：数据排序字段
     * order：升序或降序
     * name：广告标题
     * content：广告内容
     *
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求行参数
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String name = req.getParameter("name");
        String content = req.getParameter("content");
        //校验参数
        Integer page = null;
        Integer limit = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //调用service方法，返回一个广告list
        List<MarketAd> adList = adService.list(page, limit, sort, order, name, content);
        //将list响应出去
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(adList)));


    }
}
